const open = require('open');

const express = require('express');
const bodyParser = require('body-parser');

const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('./webpack.config');

// 实例化 Express
const app = express();
const compiler = webpack(webpackConfig);

// 使用 WebpackDevMiddleware 中间件
app.use(webpackDevMiddleware(compiler, {
  publicPath: '/__build__/',
  stats: {
    colors: true,
    chunks: false
  }
}));

// 使用 WebpackHotMiddleware 热更新中间件
app.use(webpackHotMiddleware(compiler));

// 使用静态文件中间件
app.use(express.static(__dirname));

// 使用请求体转换中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 获取路由
const router = express.Router();

// simple
router.get('/simple/get', (req, res) => {
  res.json({ message: 'hello world' });
});

// base
router.get('/base/get', (req, res) => {
  res.json(req.query);
});

router.post('/base/post', (req, res) => {
  res.json(req.body);
});

router.post('/base/buffer', (req, res) => {
  let msg = [];
  req.on('data', chunk => {
    chunk && msg.push(chunk);
  });
  req.on('end', () => {
    let buffer = Buffer.concat(msg);
    res.json(buffer.toJSON());
  });
});

// error
router.get('/error/get', (req, res) => {
  if (Math.random() > 0.5) {
    res.json({
      msg: 'hello world'
    });
  } else {
    res.status(500);
    res.end();
  }
});

router.get('/error/timeout', (req, res) => {
  setTimeout(() => {
    res.json({
      msg: 'hello world'
    });
  }, 5000);
});

app.use(router);

const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'development';
module.exports = app.listen(port, () => {
  const url = `http://127.0.0.1:${port}`;
  console.log(`Server listening on ${url}, Ctrl+C to stop.`);
  if (env === 'development') {
    open(url);
  }
});
